import axios, { AxiosError } from "axios";
export interface Result<T = any> {
  code: number;
  data: T;
  msg: string;
}

// 创建实例
const instance = axios.create({
  timeout: 8000,
  timeoutErrorMessage: "请求超时，请稍后再试",
  withCredentials: true,
  headers: {
    icode: "42F573FBA4EBBC1B",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.get("token");
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return {
      ...config,
    };
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use((response) => {
  const data: Result = response.data;
  if (response.config.responseType === "blob") return response;
  if (data.code === 500001) {
    localStorage.remove("token");
    location.href = "/login?callback=" + encodeURIComponent(location.href);
  } else if (data.code != 0) {
    return Promise.resolve(data);
  } else {
    Promise.reject(data);
  }
  return data.data;
});

interface IConfig {
  showLoading?: boolean;
  showError?: boolean;
}
export default {
  get<T>(
    url: string,
    params?: object,
    options: IConfig = { showLoading: true, showError: true }
  ): Promise<T> {
    return instance.get(url, { params, ...options });
  },
  post<T>(url: string, params?: object): Promise<T> {
    return instance.post(url, params);
  },
  downloadFile(url: string, data: any, fileName = "fileName.xlsx") {
    instance({
      url,
      data,
      method: "post",
      responseType: "blob",
    }).then((response) => {
      const blob = new Blob([response.data], {
        type: response.data.type,
      });
      const name = (response.headers["file-name"] as string) || fileName;
      const link = document.createElement("a");
      link.download = decodeURIComponent(name);
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  },
};
